package trefliq.EJB.sessionbeans;

import java.util.Collection;
import java.util.List;
import javax.annotation.security.PermitAll;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import trefliq.EJB.entities.Cart;
import trefliq.EJB.entities.CartItem;
import trefliq.EJB.entities.Movie;

/**
 *
 * @author Brandon
 */
@Stateless
@LocalBean
@PermitAll // (by default, allow all, restrict what's necessary)
public class CartSession {

   @PersistenceContext(unitName="trefliqPU")
   private EntityManager em;
   
   public Cart createCart(Cart c) { 
       em.persist(c);
       return c; 
   }
   
   public Cart deleteCart(Cart c) { 
       Cart cart = em.find(Cart.class, c.getId()); 
       em.remove(cart);
       return cart;
   }
   
    //TODOSEC: @RolesAllowed({SecurityRole.ADMIN, SecurityRole.EMPLOYEE})
   public List<Cart> getAllCarts() {
       return em.createNamedQuery("findAllCarts", Cart.class).getResultList();
   }
   
   public Cart getCartById(Long cartId) { 
        return em.createNamedQuery("findCartById", Cart.class).
                    setParameter("id", cartId).getSingleResult();
       
   }
   
   public List<Cart> getCartByStatus(Cart.Status status) { 
       return em.createNamedQuery("findCartByStatus", Cart.class).
                    setParameter("status", status).getResultList();
   }
   
   public void deleteCartItem(Cart c, Movie movie) { 
       Cart cart = em.createNamedQuery("findCartById", Cart.class).
                    setParameter("id", c.getId()).getSingleResult();
       Collection<CartItem> managedItem = cart.getCartItemCollection();
       
       CartItem i = null; 
       for (CartItem item : managedItem) 
           if (item.getMovieid().equals(movie))
               i = em.createNamedQuery("CartItem.findById", CartItem.class).
                    setParameter("id", item.getId()).getSingleResult();
       cart.deleteCartItem(i);
   }
   
   public void addCartItem(Cart c, Movie movie, int quantity) { 
       Cart cart = em.createNamedQuery("findCartById", Cart.class).
                    setParameter("id", c.getId()).getSingleResult();
       em.persist(movie); 
       CartItem item = new CartItem(); 
       item.setCartid(cart);
       item.setMovieid(movie);
       em.persist(item);
       CartItem managedItem = em.createNamedQuery("CartItem.findById", CartItem.class).
                    setParameter("id", item.getId()).getSingleResult();
       
       cart.addCartItem(managedItem);
   }
      
}